import {Component, OnInit, ViewChild, ElementRef} from '@angular/core';

import {defaultConfig} from 'app/theme/datatables-config-default';
import 'datatables';

import {ScoreInputService, ScoreInfo} from './score-input.service';
@Component({
  selector: 'score-input',
  templateUrl: 'score-input.component.html',
  styleUrls: ['score-input.component.scss'],
})
export class ScoreInputComponent implements OnInit {

  @ViewChild('scoreTable') scoreTable: ElementRef;
  private scoreInputListApi: string = '/water/certificate';
  private $dataTable: any;
  private searchForm: ScoreInputSearchForm = new ScoreInputSearchForm();

  private errorShow = false;

  constructor(private scoreInputService: ScoreInputService) {
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.$dataTable = jQuery(this.scoreTable.nativeElement).DataTable(this.getDataTableConfig());
  }

  search() {
    this.$dataTable.draw();
  }

  save() {
    let $inputs = this.$dataTable.$('input');
    let scores: ScoreInfo[] = [];
    let data = this.$dataTable.data();

    for (let index = 0; index < $inputs.length; index++) {
      let val = $inputs[index].value;
      if (val !== '' && val !== null && val !== undefined) {
        let scoreInfo = new ScoreInfo();
        scoreInfo.score = val;
        scoreInfo.ids = data[index].ids;
        scores.push(scoreInfo);
      }
    }

    this.scoreInputService.saveScore(scores).then(resp => {
      if (resp.status === 'success') {
        this.$dataTable.draw();
      }
    });
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private getDataTableConfig() {
    let self = this;
    let customConfig: any = {
      'ajax': {
        'url': this.scoreInputListApi,
        'data': function (d) {
          d.idcard = self.searchForm.idcard;
          d.name = self.searchForm.name;
          d.companyname = self.searchForm.companyname;
          d.type = self.searchForm.type;
          d.score = self.searchForm.score;
        }
      },
      'columns': [
        {'data': 'name'},
        {'data': 'sex'},
        {'data': 'idcard'},
        {'data': 'education'},
        {'data': 'companyname'},
        {'data': 'industry'},
        {'data': 'technicaltitles'},
        {'data': 'type'},
        {'data': 'submittime'},
        {
          'targets': 9, 'render': function (data, type, row) {
          return  `<input type="number" maxlength="5" value=${row.score}>`;
        }
        }
      ]
    };
    return Object.assign({}, defaultConfig, customConfig);
  }
}

export class ScoreInputSearchForm {
  idcard: string = '';
  name: string = '';
  companyname: string = '';
  type: string = '';
  score: string = '';
}
